package com.netease.research.service.impl;

import com.netease.research.Vo.ProductListVo;
import com.netease.research.common.Const;
import com.netease.research.common.ServerResponse;
import com.netease.research.dao.ProductMapper;
import com.netease.research.pojo.Product;
import com.netease.research.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("iProductService")
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public ServerResponse<List<ProductListVo>> listAll() {
        List<Product> productList = productMapper.selectAll();
        List<ProductListVo> productListVoList = this.assembleProductListVo(productList);
        return ServerResponse.createBySuccess(productListVoList);
    }

    @Override
    public ServerResponse<List<ProductListVo>> listUnBuy() {
        List<Product> productList = productMapper.selectUnBuy();
        List<ProductListVo> productListVoList = this.assembleProductListVo(productList);
        return ServerResponse.createBySuccess(productListVoList);
    }

    private List<ProductListVo> assembleProductListVo(List<Product> productList) {
        List<ProductListVo> productListVoList = new ArrayList<>(productList.size());
        for (Product product : productList) {
            ProductListVo vo = new ProductListVo();
            vo.setId(product.getId());
            vo.setTitle(product.getTitle());
            vo.setPrice(product.getPrice());
            vo.setStatus(product.getStatus());
            vo.setPicUrl(product.getPicUrl());
            productListVoList.add(vo);
        }
        return productListVoList;
    }

    @Override
    public ServerResponse<Product> publishProduct(Product product){
        product.setStatus(Const.ProductStatus.AVAILABLE);
        productMapper.insert(product);
        return ServerResponse.createBySuccess(product);
    }

    @Override
    public ServerResponse<Product> show(Integer productId){
        Product product=productMapper.selectByPrimaryKey(productId);
        return ServerResponse.createBySuccess(product);
    }

    @Override
    public ServerResponse<Product> edit(Product product){
        int count = productMapper.updateByPrimaryKeySelective(product);
        return ServerResponse.createBySuccess(product);
    }

    @Override
    public ServerResponse<Product> delete(Integer id){
        int count = productMapper.deleteByPrimaryKey(id);
        return ServerResponse.createBySuccess();
    }
}
